package com.shockweb.common.log;

import java.util.List;

//import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import com.shockweb.common.log.LogManager;

/**
 * POJO aop 切面： 业务切面，controller层操作动作执行时间
 *
 * @author 彭明华 2017.06.30
 */
public class OptLogAop {


    /**
     * 是否记录log
     */
    private boolean log = true;
    /**
     * 设置是否记录log
     * @param log
     */
    public void setLog(boolean log){
    	this.log = log;
    }
    
    
    List<String> lists = null;
    
    public void setSpecials(List<String> lists){
    	this.lists = lists;
    }
    /**
     * 手动控制调用核心业务逻辑，以及调用前和调用后的处理,
     * <p>
     * 注意：当核心业务抛异常后，立即退出，转向After Advice
     * 执行完毕After Advice，再转到Throwing Advice
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    	if(log){
            long st = System.currentTimeMillis();
            Object retVal = null;
            Object target = pjp.getTarget();
        	String bs = pjp.getSignature().toString(); //切入点类名.方法
            String operation = bs.substring(bs.indexOf(" ")).trim(); //切掉 前面的返回类型和空格
            

            boolean flag = true;
            if(lists!=null){
            	for(String l:lists){
            		if(operation.startsWith(l)){
            			flag = false;
            			break;
            		}
            	}
            }
            //调用核心逻辑
            try{
            	if(flag){
            		LogManager.start(target.getClass(), operation);
            	}
            	retVal = pjp.proceed();
            	if(flag){
                	long et = System.currentTimeMillis();
                	LogManager.end(target.getClass(),et - st, operation);
            	}
            }catch(Throwable ex){
            	if(flag){
	            	long et = System.currentTimeMillis();
	            	LogManager.error(target.getClass(),et - st, operation,pjp.getArgs() , ex);
            	}
            	throw ex;
            }
            return retVal;
    	}else{
    		return pjp.proceed();
    	}
    }
}